package com.bluexmicro.android.upgradebox.screen.file

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Environment
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.io.File

class FileViewModel : ViewModel() {

    private val externalDir: File = Environment.getExternalStorageDirectory()

    val hasPermission = mutableStateOf(false)
    val folders = mutableStateListOf<File>()
    val files = mutableStateOf<List<File>>(emptyList())

    //只是选择的文件
    private val _selectedFile = MutableStateFlow<File?>(null)
    val selectedFile: StateFlow<File?> = _selectedFile


    fun checkPermission(context: Context) {
        hasPermission.value = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Environment.isExternalStorageManager()
        } else {
            ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED
        }
    }

    fun resetSelect() {
        _selectedFile.value = null
    }

    private fun loadCurrentFiles() {
        if (folders.isNotEmpty()) {
            files.value = folders.last().listFiles(FileUtils.binFilter)?.asList()?.sortedBy {
                it.nameWithoutExtension
            }?.sortedBy {
                it.isFile
            } ?: emptyList()
        } else {
            files.value = emptyList()
        }
    }

    /**
     * 加载文件夹下的文件
     */
    fun pick(file: File) {
        if (file.isFile) {
            if (_selectedFile.value == file) {
                _selectedFile.value = null
            } else {
                _selectedFile.value = file
            }
        } else {
            _selectedFile.value = null
            val position = folders.indexOf(file)
            if (position in folders.indices) {
                if (position != folders.lastIndex) {
                    folders.removeRange(position + 1, folders.size)
                }
            } else {
                folders.add(file)
            }
            loadCurrentFiles()
        }
    }


    init {
        folders.add(externalDir)
        loadCurrentFiles()
    }
}